package com.example.controller;

import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户控制器
 *
 * @author System
 * @date 2024
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody User user) {
        try {
            // 参数验证
            if (user == null || user.getUsername() == null || user.getPassword() == null ||
                    user.getEmail() == null) {
                return Result.badRequest("参数不完整");
            }

            // 检查用户名是否已存在
            if (userService.isUsernameExists(user.getUsername())) {
                return Result.error("用户名已存在");
            }

            // 检查邮箱是否已存在
            if (userService.isEmailExists(user.getEmail())) {
                return Result.error("邮箱已被注册");
            }

            boolean success = userService.register(user);
            if (success) {
                logger.info("用户注册成功: {}", user.getUsername());
                return Result.success("注册成功");
            } else {
                return Result.error("注册失败");
            }
        } catch (Exception e) {
            logger.error("用户注册异常", e);
            return Result.error("系统异常");
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody User user, HttpSession session) {
        try {
            if (user == null || user.getUsername() == null || user.getPassword() == null) {
                return Result.badRequest("用户名和密码不能为空");
            }

            User loginUser = userService.login(user.getUsername(), user.getPassword());
            if (loginUser != null) {
                // 登录成功，将用户信息存入session
                session.setAttribute("user", loginUser);
                logger.info("用户登录成功: {}", user.getUsername());
                return Result.success("登录成功", loginUser);
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            logger.error("用户登录异常", e);
            return Result.error("系统异常");
        }
    }

    /**
     * 用户退出登录
     */
    @PostMapping("/logout")
    @ResponseBody
    public Result logout(HttpSession session) {
        try {
            session.removeAttribute("user");
            session.invalidate();
            return Result.success("退出成功");
        } catch (Exception e) {
            logger.error("用户退出异常", e);
            return Result.error("系统异常");
        }
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    @ResponseBody
    public Result getCurrentUser(HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user != null) {
                return Result.success("获取成功", user);
            } else {
                return Result.unauthorized("未登录");
            }
        } catch (Exception e) {
            logger.error("获取当前用户异常", e);
            return Result.error("系统异常");
        }
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    @ResponseBody
    public Result getUserById(@PathVariable Long id) {
        try {
            User user = userService.getUserById(id);
            if (user != null) {
                return Result.success("查询成功", user);
            } else {
                return Result.notFound("用户不存在");
            }
        } catch (Exception e) {
            logger.error("查询用户异常: id={}", id, e);
            return Result.error("系统异常");
        }
    }

    /**
     * 查询所有用户
     */
    @GetMapping("/list")
    @ResponseBody
    public Result getAllUsers() {
        try {
            List<User> users = userService.getAllUsers();
            return Result.success("查询成功", users);
        } catch (Exception e) {
            logger.error("查询所有用户异常", e);
            return Result.error("系统异常");
        }
    }

    /**
     * 分页查询用户
     */
    @GetMapping("/page")
    @ResponseBody
    public Result getUsersByPage(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "10") int size) {
        try {
            List<User> users = userService.getUsersByPage(page, size);
            int total = userService.getUserCount();

            // 构建分页结果
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("list", users);
            result.put("total", total);
            result.put("page", page);
            result.put("size", size);
            result.put("pages", (total + size - 1) / size);

            return Result.success("查询成功", result);
        } catch (Exception e) {
            logger.error("分页查询用户异常: page={}, size={}", page, size, e);
            return Result.error("系统异常");
        }
    }

    /**
     * 根据关键词搜索用户
     */
    @GetMapping("/search")
    @ResponseBody
    public Result searchUsers(@RequestParam String keyword) {
        try {
            List<User> users = userService.searchUsers(keyword);
            return Result.success("搜索成功", users);
        } catch (Exception e) {
            logger.error("搜索用户异常: keyword={}", keyword, e);
            return Result.error("系统异常");
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    @ResponseBody
    public Result updateUser(@RequestBody User user, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }

            // 只能更新自己的信息
            if (!"ADMIN".equals(currentUser.getRole()) && !currentUser.getId().equals(user.getId())) {
                return Result.forbidden("只能修改自己的信息");
            }

            boolean success = userService.updateUser(user);
            if (success) {
                // 更新session中的用户信息
                User updatedUser = userService.getUserById(user.getId());
                session.setAttribute("user", updatedUser);
                return Result.success("更新成功", updatedUser);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            logger.error("更新用户异常", e);
            return Result.error("系统异常");
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    @ResponseBody
    public Result changePassword(@RequestBody(required = false) java.util.Map<String, String> params, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }

            String oldPassword = params.get("oldPassword");
            String newPassword = params.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                return Result.badRequest("参数不完整");
            }

            boolean success = userService.changePassword(currentUser.getId(), oldPassword, newPassword);
            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.error("原密码错误");
            }
        } catch (Exception e) {
            logger.error("修改密码异常", e);
            return Result.error("系统异常");
        }
    }
    /**
     * 修改密码
     */
    @PutMapping("/resetPassword")
    @ResponseBody
    public Result resetPassword(@RequestBody(required = false) java.util.Map<String, String> params, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }

            String newPassword = params.get("newPassword");

            boolean success = userService.resetPassword(currentUser.getId(), newPassword);
            if (success) {
                return Result.success("密码重置成功");
            } else {
                return Result.error("密码重置失败");
            }
        } catch (Exception e) {
            logger.error("重置密码异常", e);
            return Result.error("系统异常");
        }
    }

    /**
     * 管理员更新用户状态
     */
    @PutMapping("/status")
    @ResponseBody
    public Result updateUserStatus(@RequestBody(required = false) java.util.Map<String, Object> params, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }

            // 简单的权限检查（这里假设用户名为admin的是管理员）
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }

            Long userId = Long.valueOf(params.get("userId").toString());
            Integer status = Integer.valueOf(params.get("status").toString());

            boolean success = userService.updateUserStatus(userId, status);
            if (success) {
                return Result.success("状态更新成功");
            } else {
                return Result.error("状态更新失败");
            }
        } catch (Exception e) {
            logger.error("更新用户状态异常", e);
            return Result.error("系统异常");
        }
    }

    /**
     * 管理员删除用户
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public Result deleteUser(@PathVariable Long id, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }

            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }

            boolean success = userService.deleteUser(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            logger.error("删除用户异常: id={}", id, e);
            return Result.error("系统异常");
        }
    }

    /**
     * s数量
     */
    @GetMapping("/count")
    @ResponseBody
    public Result count() {
        try {
            return Result.success(userService.getUserCount());
        } catch (Exception e) {
            return Result.error("系统异常");
        }
    }
}